﻿using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Pyramid.Bll;
using Pyramid.Models;
using Pyramid.Security;

namespace Pyramid.Controllers {
	public class BaseController : Controller {
		private PyramidDbContext _db;

		protected new virtual CustomPrincipal User {
			get { return AccountHelper.NewInstance.GetUser(HttpContext); }
		}

		protected PyramidDbContext Db {
			get { return _db ?? (_db = new PyramidDbContext()); }
		}

		/// <summary>
		/// 直接返回Json，不作任何处理
		/// </summary>
		protected ActionResult JNormal(object model) {
			var json = JsonConvert.SerializeObject(model);
			return Content(json, "application/json");
		}

		/// <summary>
		/// 返回Json，CamelCase
		/// </summary>
		protected ActionResult J(object model) {
			var json = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});
			return Content(json, "application/json");
		}

		public ActionResult JData(object data) {
			var model = new DwzResponseModel {
				StatusCode = "200",
				Data = data
			};
			return J(model);
		}

		protected ActionResult JError(string msg = "操作失败！") {
			var model = new DwzResponseModel {StatusCode = "300", Message = msg};
			return J(model);
		}

		protected ActionResult JSuccess(string msg = "操作成功！", string navTabId = "", string rel = "", string callbackType = "", string forwardUrl = "") {
			var model = new DwzResponseModel {
				StatusCode = "200",
				Message = msg,
				NavTabId = navTabId,
				Rel = rel,
				CallbackType = callbackType,
				ForwardUrl = forwardUrl
			};
			return J(model);
		}

		protected ActionResult JTimeOut() {
			var model = new DwzResponseModel {StatusCode = "301", Message = "操作超时！"};
			return J(model);
		}

		protected ActionResult NoAuthorization(string message) {
			return View("_Error", new ErrorViewModel {Title = "访问权限受限", Message = message});
		}

		protected ActionResult Error(string message) {
			return View("_Error", new ErrorViewModel {Title = "错误提示", Message = message});
		}
	}
}